package com.hopes.bizz.risk.control.support;

/**
 * @author yumr
 * @ProjectName bizz
 * @Description TODO
 * @time 2023/7/24 14:30
 */

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import com.hopes.bizz.risk.control.vo.RiskIdentifyExcelVO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yumr
 * @ProjectName sd-sfes-web
 * @Description 风险辨识单元格合并策略
 * @time 2023/6/16 11:19
 */
public class RiskIdentifyMergeStrategy extends AbstractMergeStrategy {

    private Sheet sheet;
    private final List<RiskIdentifyExcelVO> riskIdentifyExcelVOList;

    public RiskIdentifyMergeStrategy(List<RiskIdentifyExcelVO> riskIdentifyExcelVOList) {
        this.riskIdentifyExcelVOList = riskIdentifyExcelVOList;
    }

    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer integer) {
        this.sheet = sheet;
        switch (cell.getColumnIndex()) {
            case 0: case 1: case 2: case 3: case 4: case 5: case 18: case 19: {
                this.mergeGroupColumn(RiskIdentifyExcelVO::getRiskEventId, cell.getColumnIndex());
                break;
            }
            case 6: case 7: case 8: case 9: case 10: case 11: case 12: {
                this.mergeGroupColumn(RiskIdentifyExcelVO::getControlMeasureId, cell.getColumnIndex());
                break;
            }
            case 13: {
                this.mergeGroupColumn(RiskIdentifyExcelVO::getTaskCheckContentId, cell.getColumnIndex());
                break;
            }
            default:
                break;
        }
    }

    private void mergeGroupColumn(Function<RiskIdentifyExcelVO, Long> mapper, Integer column) {
        final LinkedHashSet<Long> idSet = riskIdentifyExcelVOList.parallelStream().map(mapper).filter(Objects::nonNull).collect(Collectors.toCollection(LinkedHashSet::new));
        final Map<Long, Long> collect = riskIdentifyExcelVOList.parallelStream().filter(e -> Objects.nonNull(mapper.apply(e))).collect(Collectors.groupingBy(mapper, Collectors.counting()));
        int rowCnt = 2;
        for (Long id : idSet) {
            final int count = collect.get(id).intValue();
            if (count == 1) {
                rowCnt += count;
                continue;
            }
            final CellRangeAddress cellAddresses = new CellRangeAddress(rowCnt, rowCnt + count - 1, column, column);
            sheet.addMergedRegionUnsafe(cellAddresses);
            rowCnt += count;
        }
    }
}

